package org.tarena.dang.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
	private final static String path="/dang";
	private final static int age=365*24*60*1000;
	//添加Cookie
	public static void addCookie(String name,String value,int maxAge,HttpServletResponse response) throws UnsupportedEncodingException{
		Cookie cookie = new Cookie(name,URLEncoder.encode(value,"utf-8"));
		cookie.setMaxAge(maxAge);
		cookie.setPath(path);
		System.out.println("添加到Cookie");
		response.addCookie(cookie);
	}
	
	//添加Cookie
	public static void addCookie(String name,String value,HttpServletResponse response) throws Exception{
		addCookie(name,value,age,response);
		
	}
	
	//删除Cookie
	public static void delCookie(String name,String value,int maxAge,HttpServletResponse response) throws UnsupportedEncodingException{
		Cookie cookie = new Cookie(name,"");
		cookie.setMaxAge(0);
		cookie.setPath(path);
		response.addCookie(cookie);
	}
	
	//查找Cookie
	public static String findCookie(String name,HttpServletRequest request) throws UnsupportedEncodingException{
		Cookie[] cookies = request.getCookies();
		String value = null;
		if(cookies != null){
			for(Cookie cookie:cookies){
				if(cookie.getName().equals(name)){
					value=URLDecoder.decode(cookie.getValue(),"utf-8");
				}
			}
			
		}
		return value;
	}
	
	
	
	
	
	
	
	
	
	
	
	
}
